﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LCA.Community.DAL.Interfaces;
using LCA.Community.DAL.Model;

namespace LCA.Community.DAL
{
    /// <summary>
    /// The repository for posts data manipulation.
    /// </summary>
    public class PostsRepository : BaseRepository<Post>, IPostsRepository 
    {
        #region Fields
        private ICommentsRepository _commentsRepository;
        private IPostVotesRepository _postVotesRepository; 
        #endregion

        /// <summary>
        /// Initializes a new instance of the <see cref="PostsRepository"/> class.
        /// </summary>
        /// <param name="dataContext">The data context.</param>
        public PostsRepository(IDataServiceContext<Post> dataContext, ICommentsRepository commentsRepository, IPostVotesRepository postVotesRepository)
            :base(dataContext)
        {
            _commentsRepository = commentsRepository;
            _postVotesRepository = postVotesRepository;
        }

        /// <summary>
        /// Deletes the specified post.
        /// </summary>
        /// <param name="entity">The post.</param>
        public override void Delete(Post entity)
        {
            base.Delete(entity);

            _commentsRepository.DeleteAllPostComments(entity.RowKey);
            _postVotesRepository.DeleteAllPostVotesFromPost(entity.RowKey);
        }

        /// <summary>
        /// Gets the post by user.
        /// </summary>
        /// <param name="userID">The user ID.</param>
        /// <returns></returns>
        public List<Post> GetPostByUser(string userID)
        {
            var posts = (from post in Entities
                         where post.PartitionKey == userID
                         select post).OrderByDescending(p => p.Date).ToList();

            return posts;
        }

        /// <summary>
        /// Deletes all user posts.
        /// </summary>
        /// <param name="user">The user.</param>
        public void DeleteAllUserPosts(string user)
        {
            var posts = GetPostByUser(user);

            posts.ForEach(post => Delete(post));
        }

        /// <summary>
        /// Gets the recents posts.
        /// </summary>
        /// <value>The recents posts.</value>
        public List<Post> RecentsPosts
        {
            get 
            {
                return Entities.OrderByDescending(p => p.Timestamp).Take(10).ToList(); 
            }
        }
    }
}
